import { Controller } from 'egg';
import { Op } from 'sequelize';
import { getCurrentStimp } from '../../utils';

export default class GoodsController extends Controller {
  // 分页商品分类列表
  async list() {
    const { page, pageSize } = this.ctx.validateReq(
      'category.list',
    ).query;

    const where = {};
    const result = await this.ctx.service.goods.goodsCategory.index(page, pageSize, where);

    if (result) {
      this.ctx.success({
        data: result
      });
    }
  }

  // 所有商品分类
  async listAll() {
    const list = await this.ctx.service.goods.goodsCategory.list();
    this.ctx.success({
      data: list,
    });
  }

  // 小程序商品列表分类
  async nav() {
    const { id } = this.ctx.validateReq(
      'category.nav',
    ).query;

    const list = await this.ctx.service.goods.goodsCategory.list();
    const category = await this.ctx.service.goods.goodsCategory.model.findOne({
      where: { id }
    });

    this.ctx.success({
      data: {
        list,
        category
      },
    });
  }



  // 新建商品分类
  async create() {
    const { body } = this.ctx.validateReq('category.create');

    const isExist = await this.ctx.service.goods.goodsCategory.model.findOne({
      where: {
        name: body.name,
      }
    });

    if (isExist) {
      return this.ctx.failure({
        code: 30000,
        data: {
          name: body.name,
        },
      });
    }

    const stemp = getCurrentStimp();
    Object.assign(body, {
      create_at: stemp,
      update_at: stemp,
    });

    const result = await this.ctx.service.goods.goodsCategory.create(body);

    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        },
        status: 201,
      });
    }
  }


  // 编辑商品分类
  async update() {

    const { body, params: { id } } = this.ctx.validateReq('category.update');

    const isExist = await this.ctx.service.goods.goodsCategory.model.findOne({
      where: {
        id: { [Op.ne]: id },
        name: body.name,
      }
    });

    if (isExist) {
      return this.ctx.failure({
        code: 30000,
        data: {
          name: body.name,
        },
      });
    }

    const result = await this.ctx.service.goods.goodsCategory.update(id, body);

    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        },
        status: 201,
      });
    }
  }


  // 删除分类
  async destroy() {
    const { params: { id } } = this.ctx.validateReq('category.delete');

    const result = await this.ctx.service.goods.goodsCategory.destroy(id);

    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        },
        status: 201,
      });
    }
  }

}
